package com.qying.jvm.classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @Author 秦扬
 * @Date 2021/9/7 20:29
 */
public class TestClassLoader extends ClassLoader {

    private String name;

    public TestClassLoader(ClassLoader parent, String name){
        super(parent);
        this.name = name;
    }



    @Override
    public String toString() {
        return "TestClassLoader{" +
                "name='" + name + '\'' +
                '}';
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        Class<?> clazz = null;
        //ClassLoader system = getSystemClassLoader();

        try {
          //  clazz = system.loadClass(name);
        }catch (Exception e) {

        }

        if (clazz != null) {
            return clazz;
        }

        clazz = findClass(name);

        return clazz;

    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        InputStream is = null;
        byte[] data = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            is = new FileInputStream(new File("C:\\gomeSoft\\qying-rpc\\qying-study\\target\\classes\\com\\qying\\jvm\\classloader\\Test.class"));
            int c = 0 ;
            while (-1 != (c= is.read())) {
                baos.write(c);
            }
            data = baos.toByteArray();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
                baos.close();
            }catch (Exception e) {

            }

        }

        return this.defineClass(name, data, 0, data.length);

    }

    public static void main(String[] args) throws Exception {
        TestClassLoader classLoader = new TestClassLoader(TestClassLoader.class.getClassLoader(), "TestLoaderN");

        Class clazz;

        clazz = classLoader.loadClass("com.qying.jvm.classloader.Test");
        Object o = clazz.newInstance();

        System.out.println(o.getClass().getClassLoader());
    }
}
